package com.mavenq.workflow.common;

import java.util.Map;

/**
 * 线程绑定信息
 */
public class ThreadContextHolder {

    private final ThreadLocal<Map<String, String>> threadLocal;

    private ThreadContextHolder() {
        this.threadLocal = new ThreadLocal<>();
    }

    /**
     * 获取实例
     */
    public static ThreadContextHolder getInstance() {
        return SingletonHolder.INSTANCE;
    }

    /**
     * 静态MJC类单例模式
     * 单例初使化
     */
    private static class SingletonHolder {
        private static final ThreadContextHolder INSTANCE = new ThreadContextHolder();
    }

    /**
     * 当前线程放置共享信息（用完执行clear()，防止内存泄漏）
     *
     * @param map 共享信息
     */
    public void setContext(Map<String, String> map) {
        threadLocal.set(map);
    }

    /**
     * 获取当前线程共享信息
     *
     * @return 共享信息
     */
    public Map<String, String> getContext() {
        return threadLocal.get();
    }

    /**
     * 清空上下文：（防止内存泄漏）
     */
    public void clear() {
        threadLocal.remove();
    }
}
